// scripts/build-zip.ts
import * as fs from 'fs';
import * as path from 'path';
import * as archiver from 'archiver';
import * as dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

// 获取项目名
const projectName = process.env.VITE_NAME || 'project';

// 获取当前时间并格式化
const now = new Date();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');

// 构造文件名
const fileName = `${projectName}-${month}${day}${hours}${minutes}.zip`;

// 确保 zip 目录存在
const zipDir = path.resolve(__dirname, '..', 'zip');
if (!fs.existsSync(zipDir)) {
  fs.mkdirSync(zipDir, { recursive: true });
}

// 设置输出路径到 zip 文件夹
const outputPath = path.resolve(zipDir, fileName);
// const outputPath = path.resolve(__dirname, '..', fileName);

// 创建输出流
const output = fs.createWriteStream(outputPath);
const archive = archiver('zip', {
  zlib: { level: 9 } // 最大压缩级别
});

// 监听打包完成事件
output.on('close', function () {
  console.log(`打包完成: ${fileName} (${archive.pointer()} bytes)`);
});

// 监听打包错误事件
archive.on('error', function (err) {
  throw err;
});

// 关联输出流和归档对象
archive.pipe(output);

// 添加 dist 目录到归档
archive.directory(path.resolve(__dirname, '..', 'dist'), false);

// 完成归档
archive.finalize();